import { defineComponent, onMounted, watch, shallowRef } from 'vue'

import type { mapViewPropsType } from './typings'
import useAMap from '~/hooks/useAMap'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'MapView',
  props: ['id', 'marker'],
  emits: ['lnglatSet'],
  setup(props: mapViewPropsType, { expose, emit }) {
    const userState = useVuexGetters('user', ['userAddressInfo'])
    const [mapRef, aMapRef, amapIconRef] = useAMap(
      props.id,
      {
        center: [userState.userAddressInfo.value.lon, userState.userAddressInfo.value.lat],
        zoom: 11
      },
      initAMap
    )
    const marker = shallowRef()
    watch(
      () => props.marker,
      () => {
        if (props.marker.lng) {
          setTimeout(() => {
            const { lng, lat } = props.marker
            const position = [lng, lat]
            handleAddAMapMarker(position)
          }, 1000)
        }
      },
      { deep: true }
    )
    //  添加标点
    const handleAddAMapMarker = (position: number[]) => {
      if (marker.value) {
        mapRef.value.clearMap()
      }
      marker.value = new aMapRef.value.Marker({
        icon: amapIconRef.value,
        position,
        offset: [-12, -22]
      })
      mapRef.value.add(marker.value)
      mapRef.value.setFitView()
    }
    // 根据props.marker来设置坐标点回调
    const handleSetMarkerByPropsMarkers = () => {
      if (props.marker && aMapRef.value) {
        const { lng, lat } = props.marker
        const position = [lng, lat]
        handleAddAMapMarker(position)
      }
    }

    function initAMap() {
      if (props.marker.lat) {
        const { lng, lat } = props.marker
        const position = [lng, lat]
        handleAddAMapMarker(position)
      }
      mapRef.value.on('click', (e: any) => {
        const { lnglat } = e
        handleAddAMapMarker([lnglat.lng, lnglat.lat])
        emit('lnglatSet', lnglat)
      })
    }
    onMounted(() => {})
    expose({
      mapRef,
      aMapRef,
      setMarkersByPropsMarkers: handleSetMarkerByPropsMarkers
    })
    return () => <section id={props.id}></section>
  }
})
